import requests
import json


class Base:
    def __init__(self):
        self.session = requests.Session()
        self.token = None  # 存储登录token
        self.response_data = {}  # 存储接口响应数据

    def request(self, method, url, **kwargs):
        """统一请求方法"""
        response = self.session.request(method, url, **kwargs)
        print(f"请求: {method.upper()} {url}")
        print(f"状态码: {response.status_code}")
        return response

    def post(self, url, **kwargs):
        return self.request('POST', url, **kwargs)

    def get(self, url, **kwargs):
        return self.request('GET', url, **kwargs)

    def put(self, url, **kwargs):
        return self.request('PUT', url, **kwargs)

    def delete(self, url, **kwargs):
        return self.request('DELETE', url, **kwargs)

    def extract_data(self, response, extract_rules):
        """从响应中提取数据"""
        try:
            data = response.json()
            extracted = {}
            for key, path in extract_rules.items():
                # 简单的JSON路径提取，如 "data.token"
                keys = path.split('.')
                value = data
                for k in keys:
                    value = value.get(k, '')
                extracted[key] = value
            return extracted
        except:
            return {}